package logic

import (
	"context"
	"doc-flow/docrpc/docrpc"
	"doc-flow/docrpc/internal/svc"
	"doc-flow/model"
	"errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type FlowAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFlowAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FlowAddLogic {
	return &FlowAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *FlowAddLogic) FlowAdd(in *docrpc.FlowAddRequest) (*docrpc.FlowAddResponse, error) {
	// todo: add your logic here and delete this line
	var FindFlow model.Flow
	begin := model.DB.Begin()
	err := FindFlow.FindFlowByFlowName(begin, in.Name)
	if err == nil {
		begin.Rollback()
		return nil, errors.New("稿件重复提交")
	}
	class := &model.Class{
		//Model: gorm.Model{},
		Name: in.ClassName,
	}
	err = class.FindByClassName(begin, in.ClassName)
	if err != nil {
		begin.Rollback()
		return nil, errors.New("类别添加失败")
	}

	flow := &model.Flow{
		//Model:   gorm.Model{},
		Name:    in.Name,
		Num:     int(in.Num),
		Price:   float64(in.Price),
		ClassId: int(class.ID),
	}
	err = flow.FlowAdd(begin)
	if err != nil {
		begin.Rollback()
		return nil, errors.New("稿件添加失败")
	}
	begin.Commit()
	return &docrpc.FlowAddResponse{
		FlowId: int64(flow.ID),
	}, nil
}
